/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.transas.zorlog.data.log;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Reads packets from InputStream. 
 * The format of packets is: [uint8_t id] [uint16_t size] [uint8_t[] data] [uint16_t CRC16].
 * @author amalikov
 */
public abstract class PacketReader {
	
	public PacketReader(InputStream in) {
		this.in = in;
		
		try {
			total = in.available();
		} catch (IOException ex) {
			Logger.getLogger(PacketReader.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
	
	/**
	 * Collects one packet from "in" and returns it as ByteBuffer
	 * @throws IOException 
	 */
	public abstract ByteBuffer getPacket() throws IOException;
	
	/**
	 * Returns ID of the given packet
	 */
	public abstract int getId(ByteBuffer packet);
	
	/**
	 * Returns current progress value from 0 to 100.
	 */
	public final int getProgress() {
		if (total <= 0)
			return 0;
		
		try {
			int available = in.available();
			return (int)(100 * (1 - (float)available / total) + 0.5);
		} catch (IOException ex) {
			Logger.getLogger(PacketReader.class.getName()).log(Level.SEVERE, null, ex);
			return 0;
		}
	}
	
	protected InputStream in;
	private int total;
}
